// Copyright (c) 2024, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on("Expense Allocation Doc", {
	refresh(frm) {
        // 员工费用---获取工时并计算
        if (!frm.is_new() && frm.doc.finished_allocation === 'No' && frm.doc.reverse === 1) {
            frm.add_custom_button(__('Get Timesheet Total'), () => {
                frappe.call({
					method: "calc_allocation",
					doc: frm.doc,
					freeze: true,
					freeze_message: __("正在获取项目报工并计算..."),
				}).then ((r) => {frm.refresh(); frappe.msgprint("计算完成!")})
            }).addClass('btn-primary')
        }
        // 非员工费用---获取工时并计算
        if (!frm.is_new() && frm.doc.finished_allocation === 'No') {
            frm.add_custom_button(__('Get Timesheet Total Not EMP'), () => {
                frappe.call({
					method: "calc_allocation_project",
					doc: frm.doc,
					freeze: true,
					freeze_message: __("正在获取项目报工并计算..."),
				}).then ((r) => {frm.refresh(); frappe.msgprint("计算完成!")})
            }).addClass('btn-primary')
        }
        // 获取金蝶云星空折旧费用分配表
        if (!frm.is_new() && frm.doc.finished_allocation === 'No' && frm.doc.expense_claim_type === '折旧费') {
            frm.add_custom_button(__('Get FA Expense'), () => {
                frappe.call({
                    method: "get_fa_deprdistribute",
                    doc: frm.doc,
                    freeze: true,
                    freeze_message: __("正在获取折旧分配表..."),
                }).then ((r) => {frm.refresh(); frappe.msgprint("计算完成!")})
            }).addClass('btn-primary')
        }
        // 工时分配
        if (!frm.is_new() && frm.doc.finished_allocation === 'No') {
            frm.add_custom_button(__('Expense Allocation'), () => {
                frappe.call({
					method: "allocation",
					doc: frm.doc,
					freeze: true,
					freeze_message: __("正在获取项目报工并计算..."),
				}).then ((r) => {frm.refresh(); frappe.msgprint("分配完成!")})
            }).addClass('btn-danger')
        }
        // 冲红
        if (!frm.is_new() && frm.doc.reverse === 1 && frm.doc.finished_allocation === 'Yes') {
            frm.add_custom_button(__('Reverse Myself'), () => {
                frappe.call({
					method: "reverse_myself",
					doc: frm.doc,
					freeze: true,
					freeze_message: __("正在进行..."),
				}).then ((r) => {frappe.msgprint(`成功冲销!单据链接:<a href="http://8.138.125.213:9004/app/expense-allocation-doc/${r.message.name}">${r.message.name}</a>`);})
            }).addClass('btn-danger')
        }
	},
    date: function (frm) {
		let y = parseInt(frm.doc.date.substring(0,4))
        let m = parseInt(frm.doc.date.substring(5,7))
        frm.set_value('year', y)
        frm.set_value('month', m)
        frm.set_value('role_date', frm.doc.date.replaceAll('-',''))
	},
});
